import threading

from flask import session, jsonify, request
from flask_restful import Resource

from utils.head_control.utils import get_default_head
from utils.login_helper import check_user_state
from utils.sql_info import change_user_head, get_user_info

lock = threading.Lock()


class get_head_list(Resource):

    @check_user_state
    def get(self):
        email = session.get('email')
        default_head_list = get_default_head()
        with lock:
            user_head = get_user_info(email)
        return jsonify({"list": default_head_list, "head": user_head})

    @check_user_state
    def post(self):
        email = session.get('email')
        default_head_list = get_default_head()
        with lock:
            user_head = get_user_info(email)
        return jsonify({"list": default_head_list, "head": user_head})

class change_user_head_api(Resource):

    # @check_user_state
    # def post(self):
    #     """
    #     修改头像
    #     :return: 0:失败,1:成功
    #     """
    #     form = request.form
    #     url = form.get("url")
    #     email = session.get('email')
    #     with lock:
    #         is_ok = change_user_head(email, url)
    #
    #     if is_ok:
    #         return '1'
    #     return '0'

    @check_user_state
    def post(self):
        """
        修改头像
        :return: 0:失败,1:成功
        """
        form = request.form
        url = form.get("url")
        uid = session.get('uid')
        with lock:
            is_ok = change_user_head(uid, url)

        if is_ok:
            return '1'
        return '0'
